<template>
  <!-- 饼状图容器 -->
  <div class="chart-container">
    <!-- 饼状图数据切换按钮 -->
    <div style="margin-top: 20px;">
      <el-button @click="changeOrderStatus('1')" type="primary" size="small">查看售出的产品</el-button>
<!--      <el-button @click="changeOrderStatus('3')" type="danger" size="small" style="margin-left: 10px;">查看退货的产品</el-button>-->
    </div>
    <div class="chart-wrapper">
      <div ref="piechartDom" style="height: 400px;"></div>
      <div v-if="data.productNameList.length === 0" class="no-data">暂无饼状图数据</div>
    </div>
  </div>

  <!-- 时间范围选择器 -->
  <div class="chart-container" style="margin-top: 50px">
    <el-select v-model="selectedRange" placeholder="选择时间范围" @change="loadSalesData" style="width: 200px">
      <el-option label="近一周" :value="7"></el-option>
      <el-option label="近一个月" :value="30"></el-option>
    </el-select>



    <!-- 折线图容器 -->
    <div class="chart-wrapper">
      <div ref="linechartDom" style="height: 400px;"></div>
      <div v-if="data.date.length === 0" class="no-data">暂无折线图数据</div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts';
import { loadOrderSaleDataApi, loadPipeChartDataApi } from "@/utils/API/orders/graph";

// 响应式数据
const data = reactive({
  date: [], // 折线图日期数据
  amount: [], // 折线图销量数据
  productNameList: [], // 饼状图产品名称数据
  quantityList: [], // 饼状图销量数据
});

// 选择的时间范围
const selectedRange = ref(7);

// 当前选择的订单状态，默认是 '1'（售出的产品）
const orderStatus = ref('1');

// 折线图 DOM 元素
const linechartDom = ref(null);
// 饼状图 DOM 元素
const piechartDom = ref(null);

// 折线图实例
let lineChartInstance = null;
// 饼状图实例
let pieChartInstance = null;

// 加载折线图销售数据
const loadSalesData = async () => {
  try {
    const param = { days: selectedRange.value };
    const res = await loadOrderSaleDataApi(param);

    if (res.code === '200') {
      // 更新折线图数据
      data.date = res.data.map(v => v.date);
      data.amount = res.data.map(v => v.amount);
    } else {
      // 如果接口返回错误，清空数据
      data.date = [];
      data.amount = [];
    }
  } catch (error) {
    console.error('加载折线图数据失败:', error);
    data.date = [];
    data.amount = [];
  } finally {
    // 使用 nextTick 确保 DOM 渲染完成后再渲染图表
    nextTick(() => {
      renderLineChart();
    });
  }
};

// 渲染折线图
const renderLineChart = () => {
  if (!linechartDom.value) {
    console.error('linechartDom is not available');
    return;
  }

  if (!lineChartInstance) {
    // 初始化折线图实例
    lineChartInstance = echarts.init(linechartDom.value);
  }

  // 设置折线图配置
  lineChartInstance.setOption({
    title: {
      text: '销售趋势图',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
      },
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}元',
    },
    xAxis: {
      type: 'category',
      data: data.date,
      axisLabel: {
        rotate: 45, // 如果日期过长，可以旋转45度
      },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} 元',
      },
    },
    series: [
      {
        name: '销量',
        type: 'line',
        data: data.amount,
        itemStyle: {
          color: '#409EFF', // 折线颜色
        },
        lineStyle: {
          width: 2,
        },
        smooth: true, // 平滑曲线
      },
    ],
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%',
      containLabel: true,
    },
  });
};

// 加载饼状图数据
const loadPieChartData = async () => {
  try {
    const res = await loadPipeChartDataApi({ orderStatus: orderStatus.value });
    if (res.code === '200') {
      // 更新饼状图数据
      data.productNameList = res.data.map(v => v.productName);
      data.quantityList = res.data.map(v => v.totalQuantity);
      console.log(res)
    } else {
      // 如果接口返回错误，清空数据
      data.productNameList = [];
      data.quantityList = [];
    }
  } catch (error) {
    console.error('加载饼状图数据失败:', error);
    data.productNameList = [];
    data.quantityList = [];
  } finally {
    // 使用 nextTick 确保 DOM 渲染完成后再渲染图表
    nextTick(() => {
      renderPieChart();
    });
  }
};

// 渲染饼状图
const renderPieChart = () => {
  if (!piechartDom.value) {
    console.error('piechartDom is not available');
    return;
  }

  if (!pieChartInstance) {
    // 初始化饼状图实例
    pieChartInstance = echarts.init(piechartDom.value);
  }

  // 设置饼状图配置
  pieChartInstance.setOption({
    title: {
      text: '产品销售占比',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold',
        color: '#333',
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '销量',
        type: 'pie',
        radius: '70%', // 饼状图半径
        data: data.productNameList.map((name, index) => ({
          name,
          value: data.quantityList[index],
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  });
};

// 组件挂载时加载数据
onMounted(() => {
  nextTick(() => {
    loadSalesData(); // 加载折线图数据
    loadPieChartData(); // 加载饼状图数据
  });
});

// 监听 selectedRange 变化
watch(selectedRange, () => {
  loadSalesData();
});

// 修改订单状态（点击按钮时调用）
const changeOrderStatus = (status) => {
  orderStatus.value = status;
  loadPieChartData(); // 根据新的订单状态重新加载饼状图数据
};
</script>

<style scoped>
.chart-container {
  width: 80%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart-wrapper {
  margin-bottom: 40px;
  margin-top: 20px;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 16px;
}

.el-button {
  margin-right: 10px;
}
</style>
